<template>
  <div class="shopping_car">
    <NavBar title="购物车" />
    <div>
      <div class="good_list" v-if="list.length != 0">
        <van-swipe-cell
          :name="item.cartItemId"
          :before-close="beforeClose"
          v-for="item in list"
          :key="item.cartItemId"
        >
          <div class="good_item">
            <div class="item_left">
              <van-checkbox
                @change="handGoodChecked"
                v-model="item.isChecked"
                label-disabled
              ></van-checkbox>
              <img
                class="good_img"
                :src="$filters.prefix(item.goodsCoverImg)"
                alt=""
              />
              <div class="item_titles">
                <div class="title van-ellipsis">{{ item.goodsName }}</div>
                <div class="title">
                  <van-tag type="success">交个朋友</van-tag>
                </div>
                <div class="title pic">￥{{ item.sellingPrice }}</div>
              </div>
            </div>
            <div>
              <van-stepper
                integer
                :min="1"
                :max="5"
                :model-value="item.goodsCount"
                async-change
                @change="
                  (value) => onChange(value, item.cartItemId, item.goodsCount)
                "
              />
            </div>
          </div>
          <template #right>
            <van-button style="height: 100%" square type="danger" text="删除" />
          </template>
        </van-swipe-cell>
      </div>
      <van-empty
        v-else
        class="custom-image"
        image="https://img.yzcdn.cn/vant/empty-image-error.png"
        description="购物车里没有商品"
      />
      <div style="height: 101px"></div>
      <!-- 这里如果用change 方法 会造成 model发生变化 就会执行 change事件 -->
      <van-submit-bar :price="allPic" button-text="提交订单" @submit="onSubmit">
        <van-checkbox @click="handAllChecked" v-model="allChecked"
          >全选</van-checkbox
        >
      </van-submit-bar>
    </div>
    <Tabber />
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs } from "vue";
import NavBar from "@/components/NavBar.vue";
import Tabber from "@/components/Tabber.vue";
import { getCart, modifyCart, deleteCartItem } from "@/utils/apis/cart";
import { useRouter } from "vue-router";
import { Toast, Dialog } from "vant";
import { Goods } from "@/utils/types/goods";
export default defineComponent({
  name: "shoppingCar",
  components: { Tabber, NavBar },
  setup() {
    const state = reactive({
      allChecked: false,
      value: 12,
      list: [],
      allPic: 0,
    });
    const router = useRouter();
    const onSubmit = () => {
      const isGood: boolean = state.list.some((item: Goods) => {
        return item.isChecked;
      });
      if (isGood) {
        router.push({
          path: "/statement",
        });
      } else {
        Toast("客官不选一个吗?");
      }
    };
    onMounted(async () => {
      const res = await getCart();
      res.data.forEach((item: Goods) => {
        item.isChecked = false;
      });
      state.list = res.data;
    });
    const onChange = async (value: number, cartItemId: number) => {
      if (value > 5) {
        Toast("有钱没货呀!!");
        return;
      }
      if (value < 1) {
        Toast("一个都买不起吗??");
        return;
      }
      const initCount: Goods | undefined = state.list.find(
        (item: Goods) => item.cartItemId === cartItemId
      );
      if (initCount && (initCount as Goods).goodsCount == value) {
        return;
      }
      Toast.loading({
        message: "修改中...",
        forbidClick: true,
        loadingType: "spinner",
      });
      await modifyCart({
        goodsCount: value,
        cartItemId,
      });
      state.list.forEach((item: Goods) => {
        if (item.cartItemId == cartItemId) {
          item.goodsCount = value;
        }
      });
      Toast.clear();
    };
    //计算总价
    const calculateAllPic = () => {
      const sellingPrice = state.list.map((item: Goods) => {
        return item.isChecked ? item.sellingPrice * item.goodsCount : 0;
      });
      if (sellingPrice.length != 0) {
        return sellingPrice.reduce((n, m) => n + m);
      } else {
        return 0;
      }
    };
    //单选
    const handGoodChecked = () => {
      const allCheck = state.list.every((item: Goods) => item.isChecked);
      state.allPic = calculateAllPic();
      if (allCheck) {
        state.allChecked = true;
      } else {
        state.allChecked = false;
      }
    };
    //全选 全不选
    const handAllChecked = () => {
      if (state.allChecked) {
        state.list.forEach((item: Goods) => {
          item.isChecked = true;
        });
      } else {
        state.list.forEach((item: Goods) => {
          item.isChecked = false;
        });
      }
      state.allPic = calculateAllPic();
    };
    const beforeClose = ({ position, name }: any) => {
      switch (position) {
        case "left":
        case "cell":
        case "outside":
          return true;
        case "right":
          return new Promise((resolve) => {
            console.log(resolve);
            // deleteCartItem
            Dialog.confirm({
              title: "删除商品",
              message: "确定不要了吗",
            })
              .then(async () => {
                // on confirm
                await deleteCartItem(name);
                Toast.success("删除成功");
                const res = await getCart();
                state.list = res.data;
              })
              .catch(() => {
                // on cancel
              });
          });
      }
    };
    return {
      ...toRefs(state),
      onSubmit,
      onChange,
      handGoodChecked,
      handAllChecked,
      beforeClose,
    };
  },
});
</script>
<style lang="scss" scoped>
.van-submit-bar {
  bottom: 50px;
}
.shopping_car {
  height: 100%;
  .good_list {
    .good_item {
      // height: 70px;
      display: flex;
      align-items: flex-end;
      // margin-bottom: 20px;
      justify-content: space-between;
      padding: 20px;
      box-sizing: border-box;
      border-bottom: 1px solid #eee;
      .item_left {
        display: flex;
        align-items: center;
        .good_img {
          width: 70px;
          margin: 0 6px;
        }
        .item_titles {
          height: 70px;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          font-size: 14px;
          .title {
            color: #333;
            width: 130px;
          }
          .pic {
            font-size: 16px;
            color: #f63515;
          }
        }
      }
    }
  }
}
</style>
